from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
import datetime
import wmi

# 加密密钥，长度必须为16、24或32字节，分别对应 AES-128、AES-192和AES-256
encryption_key = b'Hex_Carl_2019_AES_251oslewjs'[:16]  # 确保密钥长度为16字节


# 获取本地MAC地址
def get_local_mac_address():
    try:
        c = wmi.WMI()
        for os in c.Win32_OperatingSystem():
            device_id = os.SerialNumber.strip()
            return device_id
    except Exception as e:
        print(f"Error retrieving device ID: {e}")
        return None


# 加密授权信息
def encrypt_license_info(mac_address, start_date, validity_days):
    try:
        # 构建授权信息
        license_info = f"{mac_address}_{start_date}_{validity_days}"
        # 使用AES算法进行加密
        cipher = AES.new(encryption_key, AES.MODE_CBC)
        ct_bytes = cipher.encrypt(pad(license_info.encode(), AES.block_size))
        iv = base64.b64encode(cipher.iv).decode('utf-8')
        ct = base64.b64encode(ct_bytes).decode('utf-8')
        return iv + ct
    except Exception as e:
        print(f"Error encrypting license info: {e}")
        return None


# 解密授权信息并验证
def decrypt_and_validate_license_code(license_code, logger):
    try:
        iv = base64.b64decode(license_code[:24])  # 从授权码中提取IV
        ct = base64.b64decode(license_code[24:])  # 从授权码中提取加密后的信息

        # 使用AES算法进行解密
        cipher = AES.new(encryption_key, AES.MODE_CBC, iv)
        pt = unpad(cipher.decrypt(ct), AES.block_size).decode('utf-8')

        # print(f"解密后的明文信息: {pt}")

        # 解析授权信息
        parts = pt.split('_')
        if len(parts) != 3:
            return False, "解析授权信息时出错"

        mac_address, start_date_str, validity_days_str = parts

        # 验证MAC地址和授权时间
        local_mac_address = get_local_mac_address()
        if mac_address != local_mac_address:
            return False, "MAC地址不匹配"

        start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d").date()
        expiration_date = start_date + datetime.timedelta(days=int(validity_days_str))
        today = datetime.date.today()
        logger.log(f"有效期至{expiration_date}")
        if today < start_date or today > expiration_date:
            return False, "授权码已过期"

        return True, "授权验证通过"

    except Exception as e:
        logger.log(f"Error decrypting and validating license code: {e}")
        return False, "验证过程中出现错误"


def validate_license_code(license_code, logger):
    start_date = datetime.date.today()
    # print(start_date)
    validity_days = 90  # 授权有效天数

    mac_address = get_local_mac_address()
    if not mac_address:
        logger.log("无法获取本地MAC地址")
        return False
    else:
        # 加密授权信息
        # license_code = encrypt_license_info(mac_address, start_date, validity_days)
        # if license_code:
        #     print(f"生成的授权码：{license_code}")

        # 解密验证授权码
        valid, message = decrypt_and_validate_license_code(license_code, logger)
        if valid:
            logger.log(f"{license_code}授权验证通过，可以使用软件。")
            return True
        else:
            logger.log(f"授权验证失败：{message}")
            return False
# 示例用法
if __name__ == "__main__":
    validate_license_code()